<!-- 个人主页 -->
<template>
    <div>
        <app-head :nickname-value="userInfo.nickname" :avatarValue="userInfo.avatar"></app-head>
        <app-body>
            <div v-show="!eidtAddress">
                <div class="user-info-container">
                    <!-- 上传头像 -->
                    
                    <div class="user-info-details">                  <!--on-success事件被触发，调用此方法-->
                        <el-upload action="http://localhost:9321/file/" :on-success="fileHandleSuccess"
                            :file-list="imgFileList" accept="image/*">
                            <el-image style="width: 120px; height: 120px;border-radius: 10px;"
                                :src="$store.state.baseApi + userInfo.avatar" fit="contain"></el-image>
                        </el-upload>
                        

                        <div class="user-info-details-text">                <!--{{}}插值表达式-->
                            <div class="user-info-details-text-nickname">{{ userInfo.nickname }}</div>
                            <div class="user-info-details-text-money">余额:{{ userInfo.money }}</div>
                            <div class="user-info-details-text-money">优惠券:新人{{ userInfo.vouchers }}元优惠券</div>
                            <div class="user-info-details-text-money">用户积分:总分{{ userInfo.money/10 }}分</div>

                            <div class="user-info-details-text-time">{{ userInfo.signInTime }} 加入平台</div>
                            <div class="user-info-details-text-edit">
                                <el-button type="primary"  @click="userInfoDialogVisible = true"> 编辑个人信息</el-button>
                                <!-- <el-button type="success" plain @click="eidtAddress = true"> 编辑收货地址</el-button> -->
                                <el-button type="success" plain @click="address"> 编辑收货地址</el-button>
                            </div>
                           
                            <!-- 对话框 编辑个人信息 -->                             <!-- 绑定 userInfoDialogVisible是否展示修改框 默认false不展示该框-->
                            <el-dialog @close="finishEdit" title="编辑个人信息" :visible.sync="userInfoDialogVisible" width="400px">
                                
                                <div class="edit-tip"> 昵称</div>
                                
                                <!-- 双向绑定 输入框的值和 Vue 实例的 userInfo.nickname 属性是双向绑定--> <!-- 监听器 改变则调函数 -->
                                <el-input v-model="userInfo.nickname" :disabled="notUserNicknameEdit" @change="saveUserNickname">
                                    <!-- 事件监听  点击这个按钮，notUserNicknameEdit属性的值变成false。-->
                                    <el-button slot="append"  icon="el-icon-edit"
                                        @click="notUserNicknameEdit = false"> 修改昵称
                                    </el-button>
                                </el-input>

                                <!-- userPasswordEdit值为true  显示此<div>元素 -->
                                <div v-if="userPasswordEdit">
                                    <!-- show-password密码看不见 -->
                                    <div class="edit-tip">原密码</div>
                                    <el-input v-model="userPassword1" show-password></el-input>

                                    <div class="edit-tip">新密码</div>
                                    <el-input v-model="userPassword2" show-password></el-input>
                                    
                                    <div class="edit-tip">确认新密码</div>
                                    <el-input v-model="userPassword3" show-password></el-input>
                                    
                                    <div class="edit-tip"></div>
                                    <el-button @click="savePassword" type="primary" plain> 确认修改密码</el-button>
                                </div>

                                <!-- userPasswordEdit值为false  显示此<div>元素 -->
                                <div v-else>
                                    <div class="edit-tip">密码</div>
                                    <el-input value="123456" :disabled="true" show-password>
                                       
                                        <!-- 用户点击按钮时  userPasswordEdit属性的值设置为true -->
                                        <el-button slot="append"  icon="el-icon-edit"
                                            @click="userPasswordEdit = true"> 修改密码
                                        </el-button>
                                    </el-input>
                                </div>

                                <!-- 确认按钮  userInfoDialogVisible属性的值设置为false 不再展示-->
                                <span slot="footer" class="dialog-footer">
                                    <el-button @click="userInfoDialogVisible = false" type="primary"> 确认</el-button>
                                </span>
                            </el-dialog>
                        </div>
                    </div>
                </div>

                <div class="idle-container">
                      <!-- 点击一个选项卡，activeName的值会自动更新为被点击的选项卡的名字-->
                    <!-- 当activeName值改变时，当前激活的选项卡会自动更新为 activeName 对应的选项卡-->
                    <el-tabs v-model="activeName" @tab-click="handleClick">
                        <el-tab-pane label="购物车" name="3"></el-tab-pane>
                        <el-tab-pane label="我买到的" name="5"></el-tab-pane>
                    </el-tabs>

                    <div class="idle-container-list">
                    
                        <!-- 遍历dataList,每一项数据被赋值给 item，索引被赋值给 index -->
                        <div v-for="(item, index) in dataList[activeName - 1]" :key="index" class="idle-container-list-item">
                            <div class="idle-container-list-item-detile" @click="toDetails(activeName, item)">
                                <!-- 展示商品图片 -->
                                <el-image style="width: 115px; height: 115px;" :src="$store.state.baseApi + item.imgUrl"
                                    fit="cover">
                                    <div slot="error" class="image-slot">
                                        <i class="el-icon-picture-outline">无图</i>
                                    </div>
                                </el-image>
                                <!-- 展示文字 -->
                                <div class="idle-container-list-item-text">
                                    <!-- 商品名字 -->
                                    <div class="idle-container-list-title">
                                        {{ item.idleName }}
                                    </div>
                                    <!-- 商品详细描述 -->
                                    <div class="idle-container-list-idle-details">
                                        {{ item.idleDetails }}
                                    </div>
                                    <!-- 对商品操作时间 -->
                                    <div class="idle-container-list-idle-time">{{ item.timeStr }}</div>

                                    <!-- 价钱\状态和操作按钮 -->
                                    <div class="idle-item-foot">
                                        <!-- 价钱和状态 -->
                                        <div class="idle-prive">￥{{ item.idlePrice }}
                                            <!--activeName 只有我卖出的,我买到的,显示购买状态orderStatus,否在显示空字符串-->
                                            {{ (activeName === '5') ? orderStatus[item.orderStatus] : '' }}
                                        </div>
                                        <el-button v-if="activeName === '3'" type="primary" plain @click.stop="buyNow(item, index)">直接购买</el-button>

                                        <el-button v-if="activeName === '5'" type="danger" plain >退货</el-button>

                                        <!-- 按钮5不显示按钮 -->
                                        <el-button v-if="activeName !== '5'" type="danger" plain
                                            @click.stop="handle(activeName, item, index)">{{ handleName[activeName - 1] }}<!-- 监听事件 -->
                                        </el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </app-body>
        <app-foot></app-foot>
    </div>
</template>

<script>
import AppHead from '../common/AppMeHeader.vue';
import AppBody from '../common/AppPageBody.vue'
import AppFoot from '../common/AppFoot.vue'

export default {
    name: "me",//组件的名字，不影响路由
    components: {//使用这些组件
        AppHead,
        AppBody,
        AppFoot
    },
    data() {//组件的初始数据
        return {
            imgFileList: [],
            addressInfo: {
                consigneeName: '',
                consigneePhone: '',
                provinceName: '',
                cityName: '',
                regionName: '',
                detailAddress: '',
                defaultFlag: false
            },
            activeName: '3',//起始进入到 我发布的 我下架的 购物车 我卖出的 我买到的
            handleName: [' 下架', ' 删除', ' 撤出购物车', '', ''],//五个选项卡对应的操作按钮 数组
            dataList: [//五个选项卡对应的数据 数组
                [],//dataList[0]我发布的
                [],//dataList[1]我下架的
                [],//dataList[2]我买到的
                [],//dataList[3]我卖出的
                [],//dataList[4]我收藏的
                [],
                [],
                [],
                [],
                [],
            ],
            orderStatus: ['待付款', '待发货', '待收货', '已完成', '已取消'],//订单状态 数组
            userInfoDialogVisible: false,
            notUserNicknameEdit: true,
            userPasswordEdit: false,//密码编辑框  默认不显示
            userPassword1: '',
            userPassword2: '',
            userPassword3: '',
            eidtAddress: false,
            selectedOptions: [],//存放默认值
            userInfo: {//用户信息
                accountNumber: "",
                avatar: "",
                nickname: "",
                signInTime: "",
                sex: "",
                bank: "",
                score: 0,
                vouchers: 0,
                money: 0
            },
            addressData: []
        };
    },
    created() {//生命周期钩子，页面加载时调用
        if (!this.$globalData.userInfo.nickname) {//不存在则请求用户信息
            this.$api.getUserInfo().then(res => {//请求用户信息
                if (res.status_code === 1) {
                    res.data.signInTime = res.data.signInTime.substring(0, 10);
                    console.log(res.data);
                    this.$globalData.userInfo = res.data;
                    this.userInfo = this.$globalData.userInfo;
                }
            })
        } else {//存在用户信息则直接赋值
            this.userInfo = this.$globalData.userInfo;
            console.log(this.userInfo);
        }
        this.getMyOrder();//获取订单信息
        this.getMyFavorite();//获取购物车信息
    },
    methods: {
        getMyFavorite() {//购物车
            this.$api.getMyFavorite().then(res => {
                console.log('getMyFavorite', res);
                if (res.status_code === 1) {//成功有响应
                    for (let i = 0; i < res.data.length; i++) {//遍历res里面的data数组
                        let pictureList = JSON.parse(res.data[i].idleItem.pictureList);//解析idleItem.pictureList属性（JSON字符串），并赋值给pictureList
                        this.dataList[2].push({//dataList[2]购物车
                            favoriteId: res.data[i].id,//收藏车的id
                            id: res.data[i].idleItem.id,//商品id
                            imgUrl: pictureList.length > 0 ? pictureList[0] : '',//商品图片
                            idleName: res.data[i].idleItem.idleName,
                            idleDetails: res.data[i].idleItem.idleDetails,
                            timeStr: res.data[i].createTime.substring(0, 10) + " " + res.data[i].createTime.substring(11, 19),
                            idlePrice: res.data[i].idleItem.idlePrice
                        });
                    }
                }
            })
        },
        buyNow(item, index) {
            this.$api.addOrder({ 
                idleId: item.id ,
                orderPrice:item.idlePrice
            }).then(res => {
                if (res.status_code === 1) {
                    this.$message({
                        message: '购买成功！',
                        type: 'success'
                    });
                    this.dataList[2].splice(index, 1);//删除购物车中的商品
                    // 从购物车中移除已购买的商品
                    this.$api.deleteFavorite({
                        id: item.favoriteId
                    })
                } else {
                    this.$message.error('购买失败！');
                }
            }).catch(error => {
                this.$message.error('购买过程中出现错误！');
            });
        },
        getMyOrder() {//获取订单数据,添加到dataList[4] 我买到的  数组
            this.$api.getMyOrder().then(res => {
                if (res.status_code === 1) {
                    console.log('getMyOrder', res.data);
                    for (let i = 0; i < res.data.length; i++) {
                        let pictureList = JSON.parse(res.data[i].idleItem.pictureList);//JSON格式转换为JavaScript对象或数组
                        this.dataList[4].push({//dataList[4]我买到的
                            id: res.data[i].id,//订单id
                            imgUrl: pictureList.length > 0 ? pictureList[0] : '',//商品图片
                            idleName: res.data[i].idleItem.idleName,//商品名字
                            idleDetails: res.data[i].idleItem.idleDetails,//商品描述
                            timeStr: res.data[i].createTime.substring(0, 10) + " " + res.data[i].createTime.substring(11, 19),//订单时间
                            idlePrice: res.data[i].orderPrice,//商品价格
                            orderStatus: res.data[i].orderStatus//订单状态
                        });
                    }
                }
            })
        },
        handleClick(tab, event) {
            // console.log(tab, event);
            console.log(this.activeName);
        },
        saveUserNickname() {//保存昵称
            this.notUserNicknameEdit = true;
            this.$api.updateUserPublicInfo({
                nickname: this.userInfo.nickname
            }).then(res => {
                console.log(res);
                this.$globalData.userInfo.nickname = this.userInfo.nickname;
            })

        },
        savePassword() {//保存密码
            if (!this.userPassword1 || !this.userPassword2) {//原密码  新密码，一个不存在，打印提示
                this.$message.error('密码为空！');
            } else if (this.userPassword2 === this.userPassword3) {//新密码和确认密码相同
                this.$api.updatePassword({//往后端传递俩参数：原密码 新密码
                    oldPassword: this.userPassword1,
                    newPassword: this.userPassword2
                }).then(res => {//后端响应了
                    if (res.status_code === 1) {//后端返回1，修改成功
                        this.userPasswordEdit = false;//改完密码后，密码编辑框不再展示
                        this.$message({//弹出提示框
                            message: '修改成功！',
                            type: 'success'
                        });
                        this.userPassword1 = '';
                        this.userPassword2 = '';
                        this.userPassword3 = '';
                    } else {
                        this.$message.error('旧密码错误，修改失败！');
                    }
                })
            } else {
                this.$message.error('两次输入的密码不一致！');
            }
        },
        address(){
            this.$router.push({ path: '/address' });
        },
        finishEdit() {//关闭编辑框 调用的方法
            this.notUserNicknameEdit = true;//姓名编辑框不再展示
            this.userInfoDialogVisible = false;//false编辑框不再展示
            this.userPasswordEdit = false;
        },

        toDetails(activeName, item) {//跳转到详情页
            if (activeName === '5') {
                this.$router.push({ path: '/order', query: { id: item.id } });
            } else {
                this.$router.push({ path: '/details', query: { id: item.id } });
            }
        },
    
        //购物车--撤出购物车 对这个按钮进行操作
        //商品数据库的idle_status:0删除  1上架在卖  2下架
        handle(activeName, item, index) {//根据 activeName 的值来更新闲置物品的状态
            console.log(activeName, item, index);
            this.$confirm('是否确认？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                if (activeName === '3') {//购物车
                    this.$api.deleteFavorite({
                        id: item.favoriteId
                    }).then(res => {
                        console.log(res);
                        if (res.status_code === 1) {//请求成功
                            this.$message({
                                message: '已撤出购物车！',
                                type: 'success'
                            });
                            //splice(index, 1) 就表示从索引 index 开始删除一个元素。
                            this.dataList[2].splice(index, 1);//删除购物车中的商品
                        } else {
                            this.$message.error(res.msg)
                        }
                    }).catch(e => {
                    })
                }
            }).catch(() => {
            });
        },
        fileHandleSuccess(response, file, fileList) {//上传图片
            console.log("file:", response, file, fileList);
            let imgUrl = response.data;
            this.imgFileList = [];
            this.$api.updateUserPublicInfo({
                avatar: imgUrl
            }).then(res => {
                console.log(res);
                this.userInfo.avatar = imgUrl;
                this.$globalData.userInfo.avatar = imgUrl;
            })
        },     
    }
}
</script>

<style scoped>
.user-info-container {
    width: 100%;
    height: 200px;
    border-bottom: 15px solid #f6f6f6;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.user-info-details {
    display: flex;
    height: 140px;
    align-items: center;
    margin: 20px 40px;
}

.user-info-details-text {
    margin-left: 20px;
}

.user-info-details-text-nickname {
    font-size: 26px;
    font-weight: 600;
    margin: 10px 0;
}

.user-info-details-text-time {
    font-size: 14px;
    margin-bottom: 10px;
}

.user-info-splace {
    margin-right: 90px;
}

.idle-container {
    padding: 0 20px;
}

.idle-container-list {
    min-height: 55vh;
}

.idle-container-list-item {
    border-bottom: 1px solid #eeeeee;
    cursor: pointer;
}

.idle-container-list-item:last-child {
    border-bottom: none;
}

.idle-container-list-item-detile {
    height: 120px;
    display: flex;
    align-items: center;
}

.idle-container-list-item-text {
    margin-left: 10px;
    height: 120px;
    max-width: 800px;
}

.idle-container-list-title {
    font-weight: 600;
    font-size: 18px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.idle-container-list-idle-details {
    font-size: 14px;
    color: #555555;
    padding-top: 5px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.idle-container-list-idle-time {
    font-size: 13px;
    padding-top: 5px;
}

.idle-prive {
    font-size: 15px;
    padding-top: 5px;
    color: red;
}

.edit-tip {
    font-size: 14px;
    margin: 10px 5px;
}

.el-input,
.el-cascader,
.el-checkbox {
    width: 100%;
    margin-bottom: 20px;
}

.el-input__inner,
.el-cascader__input {
    border-radius: 5px;
    border: 1px solid #ccc;
    padding: 10px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.el-input__inner:focus,
.el-cascader__input.is-focus {
    border-color: #409EFF;
}

.el-button {
    border-radius: 5px;
    padding: 10px 20px;
}

.el-table {
    border-radius: 10px;
    overflow: hidden;
}

.el-table th, 
.el-table td {
    padding: 12px 10px;
}

.el-button[type="primary"] {
    background-color: #409EFF;
    border-color: #409EFF;
}

.el-button[type="danger"] {
    background-color: #f56c6c;
    border-color: #f56c6c;
}

.el-button--mini {
    padding: 5px 10px;
}

.el-button--mini[type="primary"], 
.el-button--mini[type="danger"] {
    margin-right: 10px;
}

.el-checkbox__label {
    color: #333;
    font-size: 14px;
}

.el-page-header__content {
    font-size: 18px;
    color: #333;
}

.idle-item-foot {
    width: 800px;
    display: flex;
    justify-content: space-between;
}
</style>